package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.msg.SeckillCodemsg;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_TAG
)
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private ISeckillOrderInfoService seckillOrderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("创建订单的消费者");
        //从orderMessage对象中拿出数据
        Long userId = orderMessage.getUserId();
        Long seckillId = orderMessage.getSeckillId();
        String uuid = orderMessage.getUuid();
        HashMap<String, Object> map = new HashMap<>();
        map.put("seckillId", seckillId);
        map.put("userId", userId);
        map.put("uuid",uuid);
        try {
            String orderNo = seckillOrderInfoService.doSeckill(userId, seckillId);
            map.put("data",orderNo );
            map.put("code",200 );
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_SUCCESS_DEST,map);
        } catch(Exception e) {
            map.put("code", SeckillCodemsg.SECKILL_FAIL.getCode());
            map.put("msg",SeckillCodemsg.SECKILL_FAIL.getMsg());
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_FAIL_DEST, map);
            e.printStackTrace();
        }
    }
}
